package com.my.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.my.domain.Result;
import com.my.websocket.WebSocketClients;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Aspect //这是一个切面通知类，用于对车位修改的方法添加AOP增强，添加Websocket推送功能
public class WebSocketAdviser {

    @Autowired
    private ObjectMapper objectMapper;

    @Pointcut("execution(public com.my.domain.Result com.my.service.impl.ParkingSpaceServiceImpl.*(..))")
    private void updateParkingSpacePointcut() {//切入点表达式
    }

    //AOP环绕通知
    @Around("updateParkingSpacePointcut()")
    public Object doAroundWebSocketBoardCast(ProceedingJoinPoint pjp) {
        try {
            //前置通知
            Object[] args = pjp.getArgs();
            Object resultObj = pjp.proceed(args);
            //后置通知
            if (resultObj instanceof Result) {
                Result result = (Result) resultObj;
                if (result.getFlag()) { //推送更新的车位数据
                    WebSocketClients.boardCast(objectMapper.writeValueAsString(result.getRes()));
                }
            }
            return resultObj;
        } catch (Throwable throwable) {
            //异常通知
            throwable.printStackTrace();
            return null;
        } finally {
            //最终通知
        }
    }

}
